module.exports = function ($scope, $resource, $modal, $modalInstance, toaster, item) {

    $scope.office = item;
    $scope.page = {};
    $scope.page.select_company_code = '';
    $scope.selectedCompanyMap = {};
    $scope.selectedCompanyList = [];
    $scope.company_code_list = [];
    $scope.loadSelectData = function () {
        $resource('/api/as/sc/office/findOfficeList', {}, {}).save($scope.office, function (res) {
            if (res.errcode === 0) {
                $scope.company_code_list = [];
                for (let index = 0; index < res.data.length; index++) {
                    const element = res.data[index];
                    if (!$scope.selectedCompanyMap[element.code]) {
                        $scope.company_code_list.push(element);
                    }
                }
                $scope.page.select_company_code = $scope.company_code_list[0].code;
            } else {
                toaster.error({ title: '', body: res.errmsg });
            }
        });
    }
    $scope.loadData = function () {
        $resource('/api/as/sc/office/findSelfRelationList', {}, {}).save($scope.office, function (res) {
            if (res.errcode === 0) {
                $scope.selectedCompanyList = res.data;
                for (let index = 0; index < $scope.selectedCompanyList.length; index++) {
                    const element = $scope.selectedCompanyList[index];
                    $scope.selectedCompanyMap[element.down_company_code] = element;
                }
                $scope.loadSelectData();
            } else {
                toaster.error({ title: '', body: res.errmsg });
            }
        });
    }
    $scope.loadData();

    $scope.add = function () {
        let params = {
            up_company_code: $scope.office.code,
            down_company_code: $scope.page.select_company_code,
            describe: '授权分销商'
        }
        $resource('/api/as/sc/office/createSpRelation', {}, {}).save(params, function (res) {
            if (res.errcode === 0) {
                toaster.success({ title: '', body: '添加成功' });
                $scope.loadData();
            } else {
                toaster.error({ title: '', body: res.errmsg });
            }
        });
    }

    $scope.changeState = function (index, is_stop) {
        let params = {
            up_company_code: $scope.office.code,
            is_stop: is_stop,
            down_company_code: $scope.selectedCompanyList[index].down_company_code
        }
        $resource('/api/as/sc/office/createSpRelation', {}, {}).save(params, function (res) {
            if (res.errcode === 0) {
                $scope.selectedCompanyList[index].is_stop = is_stop;
                toaster.success({ title: '', body: '修改成功' });
            } else {
                toaster.error({ title: '', body: res.errmsg });
            }
        });
    }

    $scope.ok = function () {
        $modalInstance.close();
    }

};